<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}`"
    width="720"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div>
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
        :originOption="optionsData"
      >
        <template #total_bill_variance="{ value, input }">
          <RangeWeight
            checkLabel="账单总费用"
            label="（账单总费用-系统中总费用）范围为"
            :value="value"
            @input="input"
            :optionsData="optionsData"
          />
        </template>

        <template #system_cost_variance="{ value, input }">
          <RangeWeight
            checkLabel="账单总费用"
            label="账单费用减去系统费用范围为"
            tips="(勾选了此条配置,则相应批次包裹的警告金额不为此数值范围,未勾选则默认包裹存在差异即为警告!!)"
            :value="value"
            @input="input"
            :optionsData="optionsData"
          />
        </template>
        <template #weight_variance="{ value, input }">
          <RangeWeight
            checkLabel="账单重量"
            label="账单重量减去系统重量范围为"
            tips="(勾选了此条配置,则相应批次包裹的警告重量不为此数值范围,未勾选则默认不验证包裹重量差异!!)"
            suffix="g"
            :value="value"
            @input="input"
            :optionsData="optionsData"
          />
        </template>
      </VForm>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? '关闭' : '取消' }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import VForm from '@/components/Form/index.vue'
import RangeWeight from './RangeWeight/index.vue'

import { auditDetail, updateAudit, createAudit } from '../../../api/index'

const props = defineProps({
  value: { type: Object, default: () => ({}) },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  optionsData: { type: Object, default: () => ({}) },
})

const emit = defineEmits(['update:modelValue', 'refresh', 'close'])

const formOption = {
  labelPosition: 'top',
  inline: true,
}

const rules = {
  rule_name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  fee_type: [{ required: true, message: '请选择费用类型', trigger: 'blur' }],
  submit_type: [{ required: true, message: '请选择提交方式', trigger: 'blur' }],
}

const form = ref()
const model = ref({})
const loading = ref()

const fieldList = [
  {
    field: 'rule_name',
    label: '规则名称',
    style: { width: '554px' },
  },
  {
    label: '状态',
    type: 'switch',
    field: 'status',
    itemProps: {
      activeValue: 1,
      inactiveValue: 0,
    },
  },
  {
    field: 'fee_type',
    label: '费用类型',
    type: 'select',
    originField: 'fee_type',
    style: { width: '140px' },
  },
  {
    label: '物流商',
    field: 'logistics_ids',
    type: 'select',
    options: {
      placeholder: '物流商',
      valueKey: 'logistics_id',
      labelKey: 'logistics_name',
    },
    multiple: true,
    origin: 'map.logistics',
    style: { width: '465px' },
  },
  {
    field: 'total_bill_variance',
    slot: 'total_bill_variance',
  },
  {
    field: 'system_cost_variance',
    slot: 'system_cost_variance',
  },
  {
    field: 'weight_variance',
    slot: 'weight_variance',
  },
  {
    field: 'submit_type',
    label: '提交方式',
    type: 'radio',
    originField: 'submit_type',
  },
]

watch(
  () => props.value?.id,
  val => {
    if (val) {
      getDetail(val)
    }
  }
)

const getDetail = async id => {
  try {
    const { data } = await auditDetail({ id })

    const {
      system_cost_variance_max,
      system_cost_variance_min,
      total_bill_variance_max,
      total_bill_variance_min,
      weight_variance_max,
      weight_variance_min,
      ...reset
    } = data || {}

    model.value = {
      ...reset,
      system_cost_variance: {
        min: system_cost_variance_min,
        max: system_cost_variance_max,
      },
      total_bill_variance: {
        min: total_bill_variance_min,
        max: total_bill_variance_max,
      },
      weight_variance: {
        min: weight_variance_min,
        max: weight_variance_max,
      },
    }
  } catch (e) {
    console.error(e)
  }
}

const isEdit = computed(() => {
  return !!props.value?.id
})

const handleSave = async () => {
  try {
    const formInfo = await form.value.submit()
    const {
      total_bill_variance = {},
      system_cost_variance = {},
      weight_variance = {},
    } = formInfo

    console.warn(formInfo)
    const params = {
      ...formInfo,
      total_bill_variance_min: total_bill_variance?.min,
      total_bill_variance_max: total_bill_variance?.max,
      system_cost_variance_min: system_cost_variance?.min,
      system_cost_variance_max: system_cost_variance?.max,
      weight_variance_min: weight_variance?.min,
      weight_variance_max: weight_variance?.max,
    }

    const { value: { id } = { id: '' } } = props
    const api = {
      edit: updateAudit,
      add: createAudit,
    }
    const { code, message } = await api[isEdit.value ? 'edit' : 'add']({
      id: id || undefined,
      ...params,
    })
    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    ElMessage.success(isEdit.value ? '修改成功' : '保存成功')
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning('请检查表单信息')
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  model.value = {}
  await nextTick()
  form.value.resetForm()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
